import {PreNormalized} from "./types";

function word2number(express, map) {
  return Object.keys(map).reduce(function (res, key) {
    var n;
    var r;
    var o;
    var reg;
    var u;

    n = res;
    r = key
    o = map[r];
    reg = new RegExp("(^|[ ,-/])" + r + "($|[ ,-/])", "gi");
    u = "$1" + o + "$2";
    return n.replace(reg, u).replace(reg, u);
  }, express);
}

var weekToNumber = {
  sun: "0",
  mon: "1",
  tue: "2",
  wed: "3",
  thu: "4",
  fri: "5",
  sat: "6"
};
const monthToNumber = {
  jan: "1",
  feb: "2",
  mar: "3",
  apr: "4",
  may: "5",
  jun: "6",
  jul: "7",
  aug: "8",
  sep: "9",
  oct: "10",
  nov: "11",
  dec: "12"
};
var s = {
  "@yearly": ["0", "0", "1", "1", "*"],
  "@annually": ["0", "0", "1", "1", "*"],
  "@monthly": ["0", "0", "1", "*", "*"],
  "@weekly": ["0", "0", "*", "*", "0"],
  "@daily": ["0", "0", "*", "*", "*"],
  "@midnight": ["0", "0", "*", "*", "*"],
  "@hourly": ["0", "*", "*", "*", "*"]
};

const INDEX_OF_DATE = 2
const INDEX_OF_WEEK = 4

export function preNormalize(crontabExpression: string): PreNormalized {
  const parts = crontabExpression.trim().split(/\s+/).filter(function (e) {
    return e;
  });

  const formattedParts = parts.map(function (segmentExpress, index) {
    switch (index) {
      case 3: // day of month
        return word2number(segmentExpress, monthToNumber);
      case 4:// week
        return word2number(segmentExpress, weekToNumber);
      default:
        return segmentExpress;
    }
  });

  return {
    originalParts: parts,
    parts: formattedParts,
    daysAnded: !!formattedParts[INDEX_OF_DATE] && "*" === formattedParts[INDEX_OF_DATE][0] ||
      !!formattedParts[INDEX_OF_WEEK] && "*" === formattedParts[INDEX_OF_WEEK][0]
  };
};
